import { ApiRequestQuery, ApiRequestBody } from './../types';
import { Ctx, Next } from '../types';

/**
 * 中间件验证路由请求信息
 * @export
 * @param {Ctx} ctx
 * @param {Next} next
 */
export async function validatorRouterFilter(ctx: Ctx, next: Next) {
  const { query} = ctx;
  const { body } = ctx.request;
  const routerliving = ctx.routerliving;
  // 判断get 请求对象
  if (routerliving.query) {
    Object.keys(routerliving.query).map(filter => {
      if(routerliving.query[filter][2] !== true) {
        if(query[filter] === undefined && routerliving.query[filter][1] !== undefined) {
          ctx.query[filter] = routerliving.query[filter][1];
        }
      }else{
        if(query[filter] === undefined) {
          ctx.throw(400, ctx.error(`request query ${filter} is undefined`));
        }else{
          if (query[filter] !== undefined) {
            if(!validatorFilterType(query[filter], routerliving.query[filter], ctx.validator)) {
              ctx.throw(400, ctx.error(`request query ${filter} type not is ${routerliving.query[filter][0]}`));
            }
          }
        }
      }
    });
  }
  
  // 判断post 请求对象
  if (routerliving.body) {
    Object.keys(routerliving.body).map(filter => {
      if(body[filter] === undefined) {
        ctx.throw(400, ctx.error(`request body ${filter} is undefined`));
      }
      if(!validatorFilterType(body[filter], routerliving.body[filter], ctx.validator)) {
        ctx.throw(400, ctx.error(`request body ${filter} type not is ${routerliving.body[filter][0]}`));
      }
    });
  }
  await next();
}

/**
 * 判断参数类型
 * @export
 * @param {*} source
 * @param {*} target
 * @returns {boolean}
 */
export function validatorFilterType(source: any, target: ApiRequestQuery | ApiRequestBody, validator: ValidatorJS.ValidatorStatic): boolean {

  let validate = true;
  switch(target[0]) {
    case 'number': 
      try {
        validate = validator.isNumeric(source.toString());  
      } catch (error) {
        validate = false
      }
    break;
  }

  return validate;
}